package com.hdu.mockService.handler;

import com.hdu.mockService.annotation.RandomInt;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.List;

import static com.hdu.mockService.utils.ReflectionUtils.getFieldsByTargetAnnotation;

public class IntMockHandler implements IMockHandler {

    @Override
    public void partitionMock(Object mockObj) {
        List<Field> mockIntFields = getFieldsByTargetAnnotation(mockObj.getClass(), RandomInt.class);
        if (CollectionUtils.isEmpty(mockIntFields)) {
            return;
        }
        for (Field field : mockIntFields) {
            field.setAccessible(true);
            RandomInt randomInt = field.getAnnotation(RandomInt.class);
            int min = randomInt.min();
            int max = randomInt.max();
            try {
                field.set(mockObj, getRandomInt(min, max));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    protected int getRandomInt(int min, int max) {
        return (int) (Math.random() * (max - min + 1) + min);
    }
}
